package com.james.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.james.constant.MessageConstant;
import com.james.constant.RedisMessageConstant;
import com.james.entity.Result;
import com.james.pojo.Order;
import com.james.service.OrderService;
import com.james.util.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author ACT
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String, Object> map) {
        String telephone = (String) map.get("telephone");
        //从Redis中获取验证码
        String validateCodeInRedis = jedisPool.getResource().get(
                telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //从map中获取验证
        String validateCode = (String) map.get("validateCode");
        //验证码比较（由于无短信服务，取消）

        //设置预约类型，分为微信预约、电话预约
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        Result result = null;
        try {
            result = orderService.order(map);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        if (result.isFlag()) {
            //预约成功，可以为用户发送短信
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Map<String, Object> map;
        try {
            map = orderService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
    }

}
